<template>
  <Card :bordered="false" dis-hover>
    <jgSearch
      :searchData="searchData"
      @on-enter="askDatasearch"
      @on-change-change="askDatachanges"
      @on-clear="askDatasearch"
      @click-click="openedits(-1)"
    />
    <Table
      ref="table"
      highlight-row
      :loading="loading"
      :columns="columns"
      @on-sort-change="sortchange"
      :data="list"
    >
      <template slot="info" slot-scope="{ row }">
        <div class="info">
          <img :src="row.avatar" width="40px" height="40px" alt="" />
          <div class="text">
            <p>{{ row.wechatnick }}</p>
            <p>微信号：{{ row.wechatno }}</p>
          </div>
        </div>
      </template>
      <template slot="operation" slot-scope="{ row }">
        <a
          v-hasC="{
            name: 'setting-phone-phone-update',
            flag: 'v1/setting/phone/phone-update',
          }"
          @click="openedits(row)"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-site-repair-wechat-friend-queue',
            flag: 'v1/site/repair-wechat-friend-queue',
          }"
        />
        <a
          @click="changeupdata(row)"
          v-hasC="{
            name: 'v1-site-repair-wechat-friend-queue',
            flag: 'v1/site/repair-wechat-friend-queue',
          }"
          :disabled="row.disabled"
          >同步通讯录</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-site-repair-wechat-friend-queue',
            flag: 'v1/site/repair-wechat-friend-queue',
          }"
        />
        <a
          @click="openModal(row)"
          v-hasC="{
            name: 'v1-setting-pro-business-equipment-voice-queue',
            flag: 'v1/setting/pro/business/equipment/voice-queue',
          }"
          >同步录音</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-setting-pro-business-equipment-voice-queue',
            flag: 'v1/setting/pro/business/equipment/voice-queue',
          }"
        />
        <a
          @click="del(row)"
          v-hasC="{
            name: 'v1-site-repair-wechat-friend-queue',
            flag: 'v1/site/repair-wechat-friend-queue',
          }"
          :disabled="row.disabled"
          >删除</a
        >
      </template>
    </Table>
    <div class="ivu-mt ivu-text-center">
      <Page
        show-total
        show-elevator
        show-sizer
        :total="total"
        :current.sync="params.page"
        :page-size="params.pageSize"
        :page-size-opts="pageOpts"
        @on-change="changepage"
        @on-page-size-change="changepageSize"
      />
    </div>
    <Modal
      v-model="showedit"
      :title="edits ? '新增' : '编辑'"
      @on-cancel="canceledit(modalname)"
      :mask-closable="false"
      draggable
      sticky
      reset-drag-position
    >
      <Form
        :label-width="100"
        :model="formItem"
        :ref="modalname"
        :rules="createRules"
      >
        <FormItem label="设备ID">
          <Input v-model="formItem.deviceid" placeholder="请输入设备ID" />
          <font color="red">设备ID变更，手机必须重启方可生效！</font>
        </FormItem>
        <FormItem label="所属系统" prop="system">
          <Select v-model="formItem.sys_id" :disabled="!edits">
            <Option value="1">灯塔系统</Option>
            <Option value="2">白友系统</Option>
          </Select>
        </FormItem>
        <FormItem label="设备信息">
          <Input v-model="formItem.module" placeholder="请输入设备信息" />
        </FormItem>
        <!-- <FormItem label="型号">
                    <Input v-model="formItem.module" placeholder="请输入手机型号" />
                </FormItem> -->
        <FormItem class="ivu-mb-0" v-if="!edits && changemember">
          <font color="red">设备归属人员变更，需要重启手机方可生效！</font>
        </FormItem>
        <FormItem label="部门人员" required v-if="formItem.sys_id == 1">
          <Row :gutter="24">
            <Col span="8">
              <FormItem prop="departmentId">
                <Select
                  clearable
                  placeholder="请选择部门"
                  v-model="formItem.departmentId"
                  @on-change="memberlist"
                >
                  <Option
                    v-for="item in department"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem prop="memberId">
                <Select
                  clearable
                  placeholder="请选择人员"
                  v-model="formItem.memberId"
                  @on-change="changemember = true"
                >
                  <Option
                    v-for="item in member"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="formItem.nickname" placeholder="请输入设备备注" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="canceledit(modalname)">取消</Button>
        <Button type="primary" @click="submitedit(modalname)">确定</Button>
      </div>
    </Modal>
    <!-- <Modal
            v-model="modal"
            footer-hide>
            <p style="text-align: center;font-size:16px">通讯录正在同步，请稍等</p>
        </Modal> -->
    <Modal v-model="lyModal" title="选择时间">
      <DatePicker
        type="daterange"
        v-model="lydate"
        ref="lydate"
        :options="dateOption"
        placement="bottom-end"
        placeholder="选择开始时间和结束时间"
        style="width: 300px"
      />
      <div slot="footer">
        <Button @click="lyCancel">取消</Button>
        <Button type="primary" @click="lySubmit">确定</Button>
      </div>
    </Modal>
  </Card>
</template>
<script>
import jgSearch from "@/components/search";
import mixins from "@/mixins/mixins";
import dayjs from "dayjs";
import {
  settingphonephonelist,
  settingphonephoneupdate,
  settingphonephoneadd,
  settingphonephoneinfo,
  wechatfriendQueue,
  wechatmessageQueue,
  phoneDel,
  voiceQueue,
} from "@/api/hqapi/indexone";
import util from "@/libs/util";
export default {
  name: "equipment",
  components: { jgSearch },
  mixins: [mixins],
  data() {
    return {
      changemember: false,
      searchData: {
        project: [
          {
            key: "Input",
            style: { width: "200px" },
            value: "",
            clearable: true,
            placeholder: "请输入设备ID,备注名",
            callback: "",
          },
          {
            key: "Select",
            placeholder: "系统筛选",
            clearable: false,
            style: { width: "100px" },
            value: 1,
            childList: [
              { label: "灯塔", value: 1 },
              { label: "白友", value: 2 },
            ],
            callback: "change",
          },
        ],
        button: [{ key: "新增", callback: "click" }],
      },
      columns: [
        { title: "设备ID", key: "deviceid", minWidth: 165, fixed: "left" },
        { title: "微信信息", slot: "info", minWidth: 220 },
        { title: "所属系统", key: "sys_str", minWidth: 100 },
        { title: "设备信息", key: "module", minWidth: 100 },
        { title: "备注", key: "nickname", minWidth: 140 },
        { title: "使用人", key: "realname", minWidth: 80 },
        { title: "是否在线", key: "isonline_str", minWidth: 100 },
        {
          title: "最近登录时间",
          key: "login_time",
          minWidth: 170,
          sortable: "custom",
        },
        {
          title: "更新时间",
          key: "create_time",
          minWidth: 170,
          sortable: "custom",
        },
        { title: "操作", slot: "operation", fixed: "right", minWidth: 270 },
      ],
      createRules: {
        departmentId: [
          {
            required: true,
            type: "string",
            message: "请选择部门",
            trigger: "change",
          },
        ],
        memberId: [
          {
            required: true,
            type: "string",
            message: "请选择人员",
            trigger: "change",
          },
        ],
      },
      params: {
        page: 1,
        pageSize: 20,
        keyword: "",
        sort_column: "",
        sort_order: "",
        sys_id: 1,
      },
      departments: [],
      department: [],
      member: [],
      modalname: "formItem",
      list: [],
      formItem: {
        deviceid: "",
        id: undefined,
        memberId: "",
        departmentId: "",
        nickname: "",
        module: "",
        sys_id: "1",
      },
      tableHeight: 500,
      state: false,
      modal: false,
      lyModal: false,
      lydate: [
        dayjs()
          .add(-7, "days")
          .format("YYYY-MM-DD"),
        dayjs().format("YYYY-MM-DD"),
      ],
      dateOption: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
      lyParams: {
        type: "swoole",
        imei: "",
        wechatid: "",
        start_time: "",
        end_time: "",
      },
    };
  },
  mounted() {
    // 设置表格高度
    this.tableHeight =
      window.innerHeight - this.$refs.table.$el.offsetTop - 180;
  },
  methods: {
    sortchange(e) {
      let sort = 0;
      if (e.order === "desc") {
        sort = 2;
      } else if (e.order === "asc") {
        sort = 1;
      } else {
        sort = 0;
      }
      switch (sort) {
        case 1:
          this.params.sort_order = "asc";
          break;
        case 2:
          this.params.sort_order = "desc";
          break;
        default:
          this.params.sort_order = "";
          break;
      }
      switch (e.key) {
        case "create_time":
          this.params.sort_column = "create_time";
          break;
        case "login_time":
          this.params.sort_column = "login_time";
          break;

        default:
          break;
      }
      this.initial();
    },
    initial() {
      this.funaskData = settingphonephonelist;
      this.funupdate = settingphonephoneupdate;
      this.funcreate = settingphonephoneadd;
      this.askData();
    },
    askDatas(res) {
      this.list = res.list.list.map((item) => {
        return {
          ...item,
          disabled: false,
        };
      });
      this.total = res.list.total;
      // 从cookies里取wechatid比对，过期时间5分钟
      this.list.forEach((it) => {
        let oldwechatId = util.cookies.get(`wechatwechatid-${it.wechatid}`);
        if (oldwechatId && it.wechatid == oldwechatId) {
          it.disabled = true;
        } else {
          it.disabled = false;
        }
      });
    },
    openedits(row) {
      settingphonephoneinfo({ id: row.id }).then((res) => {
        this.departments = res.department;
        for (let item of this.departments) {
          let bool = false;
          this.department.forEach((res) => {
            if (res.value === item.department_id) bool = true;
          });
          if (!bool)
            this.department.push({
              value: item.department_id,
              label: item.department_name,
            });
        }
        this.changemember = false;
        this.openedit(row);
        this.memberlist(row.did);
      });
    },
    // 同步通话记录
    changeupdata(item) {
      wechatfriendQueue({ wechatid: item.wechatid })
        .then((res) => {
          if (!item.disabled) {
            item.disabled = true;
            if (res) {
              this.$Message.success({
                content: "通讯录正在同步，请稍等",
                duration: 3,
              });
              // 往cookies里存wechatid，过期时间5分钟
              let millisecond = new Date().getTime();
              let expiresTime = new Date(millisecond + 60 * 1000 * 5);
              util.cookies.set(
                `wechatwechatid-${item.wechatid}`,
                item.wechatid,
                {
                  expires: expiresTime,
                }
              );
              setTimeout(() => {
                item.disabled = false;
              }, 300000);
            } else {
              this.$Message.error("同步失败");
            }
          }
        })
        .catch(() => {
          //
        });

      // console.log(item,'111');
    },
    del(row) {
      this.$Modal.confirm({
        title: "温馨提示",
        content: "删除后数据将不再同步，授权码回收，是否确认删除?",
        onOk: () => {
          phoneDel({ id: row.id, cid: row.cid }).then((res) => {
            this.askData();
          });
        },
      });
    },
    searchparams() {
      this.params.keyword = this.searchData.project[0].value;
      this.params.sys_id = this.searchData.project[1].value;
    },
    askDatachanges(e) {
      this.params.sys_id = e;
      this.askData();
    },
    paramscancel() {
      this.formItem = {
        deviceid: "",
        id: undefined,
        memberId: "",
        departmentId: "",
        nickname: "",
        module: "",
        sys_id: "1",
      };
    },
    paramsedit(row) {
      this.formItem = {
        deviceid: row.deviceid,
        id: row.id,
        memberId: row.accountid,
        departmentId: row.did,
        nickname: row.nickname,
        module: row.module,
        sys_id: row.sys_id,
      };
    },
    memberlist(id) {
      this.member = [];
      for (let item of this.departments) {
        if (+id === +item.department_id)
          this.member.push({ value: item.member_id, label: item.realname });
      }
    },
    paramssubmit() {
      let config;
      if (this.formItem.sys_id == 2) {
        config = {
          deviceid: this.formItem.deviceid,
          id: this.formItem.id,
          nickname: this.formItem.nickname,
          sys_id: this.formItem.sys_id,
          member_id: 0,
          department_id: 0,
          module: this.formItem.module,
        };
      } else {
        config = {
          deviceid: this.formItem.deviceid,
          id: this.formItem.id,
          member_id: this.formItem.memberId,
          department_id: this.formItem.departmentId,
          nickname: this.formItem.nickname,
          sys_id: this.formItem.sys_id,
          module: this.formItem.module,
        };
      }

      return config;
    },
    openModal(row) {
      this.lyModal = true;
      this.lyParams = {
        type: "swoole",
        imei: row.deviceid,
        wechatid: row.wechatid,
        start_time: "",
        end_time: "",
      };
    },
    lyCancel() {
      this.lyModal = false;
      this.lyParams = {
        type: "swoole",
        imei: "",
        wechatid: "",
        start_time: "",
        end_time: "",
      };
      this.lydate = [
        dayjs()
          .add(-7, "days")
          .format("YYYY-MM-DD"),
        dayjs().format("YYYY-MM-DD"),
      ];
    },
    lySubmit() {
      if (this.lydate.length > 0) {
        this.lyParams.start_time = this.lydate[0]
          ? dayjs(this.lydate[0]).format("YYYY-MM-DD")
          : "";
        this.lyParams.end_time = this.lydate[1]
          ? `${dayjs(this.lydate[1]).format("YYYY-MM-DD")}${23}:${59}`
          : "";
        voiceQueue(this.lyParams).then((res) => {
          this.$Message.success("正在同步，5分钟内请勿重复操作");
          this.lyCancel();
        });
      } else {
        this.$Message.error("请选择日期后再操作");
      }
    },
  },
};
</script>
<style lang="less" scoped>
.info {
  display: flex;
  align-items: center;
}
.info img {
  margin-right: 5px;
}
.info .text {
  font-size: 12px;
}
</style>
